package com.lzx.iteam;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.*;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.lzx.iteam.base.FindViewById;
import com.lzx.iteam.base.MyBaseActivity;
import com.lzx.iteam.bean.WeeklyDetailListData;
import com.lzx.iteam.emotion.EmotionUtil;
import com.lzx.iteam.emotion.gif.AnimatedGifDrawable;
import com.lzx.iteam.emotion.gif.AnimatedImageSpan;
import com.lzx.iteam.net.*;
import com.lzx.iteam.util.*;
import com.lzx.iteam.widget.RoundImageView;
import com.lzx.iteam.widget.TextContentView;
import com.lzx.iteam.widget.TextViewSpan;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 * **********************************
 * User: zhangshuai
 * Date: 2016年 05月 27日
 * Time: 上午9:58
 *
 * @QQ : 1234567890
 * **********************************
 */
public class WeeklyDetailActivity extends MyBaseActivity implements View.OnClickListener {


    @FindViewById(id = R.id.title_ll_back)
    private LinearLayout mLayoutBack;
    @FindViewById(id = R.id.title_tv_center)
    private TextView mTvTitle;
    @FindViewById(id = R.id.weekly_detail_layout)
    private LinearLayout mLayoutContent;
    @FindViewById(id = R.id.iv_weekly_detail_list_item_user_img)
    private RoundImageView mIvAvatar;
    @FindViewById(id = R.id.tv_weekly_detail_list_item_user_name)
    private TextView mTvUserName;
    @FindViewById(id = R.id.tv_weekly_detail_list_item_week)
    private TextView mTvWeek;
    @FindViewById(id = R.id.tv_weekly_detail_list_item_time)
    private TextView mTvTime;
    @FindViewById(id = R.id.ll_weekly_detail_list_item_content)
    private LinearLayout mLayoutWeeklyContent;
    @FindViewById(id = R.id.tv_weekly_detail_list_item_comment)
    private TextView mTvComment;
    @FindViewById(id = R.id.ll_weekly_detail_list_item_comment_list)
    private LinearLayout mLayoutCommentList;
    @FindViewById(id = R.id.ll_weekly_detail_list_bottom)
    private LinearLayout mLlBottomLayout;
    @FindViewById(id = R.id.et_weekly_detail_list_input)
    private EditText mEtCommentEdit;
    @FindViewById(id = R.id.iv_weekly_detail_list_emotion)
    private ImageView mIvEmotiom;
    @FindViewById(id = R.id.tv_weekly_detail_list_send)
    private TextView mTvSend;
    @FindViewById(id = R.id.ll_weekly_detail_list_emotion)
    private LinearLayout mEmotionLayout;
    @FindViewById(id = R.id.weekly_detail_list_emotion_viewpager)
    private ViewPager mVpEmotion;
    @FindViewById(id = R.id.weekly_detail_list_emotion_dots_container)
    private LinearLayout mLlEmotionDots;
    @FindViewById(id = R.id.weekly_detail_list_item_line)
    private View line;

    private String mGroupId;
    private String mWeeklyId;
    private String mSendMessage;
    private String[] s = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"};

    private WeeklyDetailListData weeklyData = null;

    private static final int WEEKLY_DETAIL = 10001;
    private final int ADD_COMMENT_MSG = 10002;
    private EmotionUtil mEmotionUtil;
    private Dialog mWaitDialog;


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case WEEKLY_DETAIL:
                    httpReqDlgDismiss();
                    if (msg.arg1 == 0) {
                        weeklyData = (WeeklyDetailListData) msg.obj;
                        setData();
                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(mActivity, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(mActivity, (String) msg.obj,
                                    Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                case ADD_COMMENT_MSG:
                    if (msg.arg1 == 0) {
                        ArrayList<String> nameCard = (ArrayList<String>) PreferenceUtil.getInstance(WeeklyDetailActivity.this).getCloudContact(Constants.CONTACT_NAME_CARD);
                        Map<String, String> map = new HashMap<String, String>();
                        map.put(Constants.COMMENT_USER_ID, PreferenceUtil.getInstance(WeeklyDetailActivity.this).getString(PreferenceUtil.CLIENT_USEID, "－1"));
                        if (nameCard != null && nameCard.size() > 0) {
                            map.put(Constants.COMMENT_USER_NAME, nameCard.get(0));
                        }
                        map.put(Constants.COMMENT_CREATE_TIME, System.currentTimeMillis() / 1000 + "");
                        map.put(Constants.COMMENT_CONTENT, mSendMessage);
                        if (weeklyData.comments == null) {
                            ArrayList<Map<String, String>> comments = new ArrayList<Map<String, String>>();
                            comments.add(map);
                            weeklyData.comments = comments;
                        } else {
                            weeklyData.comments.add(map);
                        }
                        setData();
                        //更新数据库
                        mLlBottomLayout.setVisibility(View.GONE);
                        mSendMessage = "";
                        mEtCommentEdit.requestFocus();
                        ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    } else {
                        Toast.makeText(mActivity, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;
            }
        }
    };


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.weekly_detail_layout);
        initEmotion();
        line.setVisibility(View.GONE);

    }

    @Override
    public void initListener() {
        mLayoutBack.setOnClickListener(this);
        mTvComment.setOnClickListener(this);
        mIvEmotiom.setOnClickListener(this);
        mEtCommentEdit.setOnClickListener(this);
        mTvSend.setOnClickListener(this);

        mEtCommentEdit.addTextChangedListener(mTextWatcher);

    }

    @Override
    public void initData() {
        mTvTitle.setText("详情");
        Intent passIntent = getIntent();
        mGroupId = passIntent.getStringExtra("groupId");
        mWeeklyId = passIntent.getStringExtra("weeklyId");
        mEtCommentEdit.requestFocus();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        mLayoutContent.setVisibility(View.GONE);
        httpReqDlgShow();
        getWeeklyDetail();

    }

    private void initEmotion() {
        mEmotionUtil = new EmotionUtil(this, mEtCommentEdit, mLlEmotionDots, mVpEmotion);
        mEmotionUtil.initStaticFaces();
        mEmotionUtil.initViewPager();
        mVpEmotion.setOnPageChangeListener(mEmotionUtil.new PageChange());
    }

    private void setData() {
        mLayoutContent.setVisibility(View.VISIBLE);
        ImageLoaderInterface.imageLoader.displayImage(weeklyData.userImg, mIvAvatar, ImageLoaderInterface.optionHeadImage);
        mTvUserName.setText(weeklyData.userName);
        mTvTime.setText(DateUtil.getChatTime(Long.parseLong(weeklyData.createTime) * 1000));
        mTvWeek.setText("周报" + s[Integer.parseInt(weeklyData.weeklyMonth)] + "月第" + s[Integer.parseInt(weeklyData.weeklyCount)] + "周");
        try {
            JSONArray content = new JSONArray(weeklyData.content);
            mLayoutWeeklyContent.removeAllViews();
            for (int i = 0; i < content.length(); i++) {
                JSONObject item = content.getJSONObject(i);
                TextContentView contentView = new TextContentView(mActivity);
                contentView.setTitleText(item.getString("field"));
                String value = item.getString("value");
                if (!StringUtil.isEmpty(value)) {
                    contentView.setContentText(value.replaceAll("\r", "\r\n"));
                }
                mLayoutWeeklyContent.addView(contentView);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (weeklyData.comments != null && weeklyData.comments.size() > 0) {
            mLayoutCommentList.setVisibility(View.VISIBLE);
            mLayoutCommentList.removeAllViews();
            for (int i = 0; i < weeklyData.comments.size(); i++) {
                final Map<String, String> commentMap = weeklyData.comments.get(i);
                TextView comment = new TextView(mActivity);

                // comment.setMovementMethod(LinkMovementMethod.getInstance());
                comment.setTextColor(getResources().getColor(
                        R.color.talk_item_comment_content));
                comment.setTextSize(14);
                String commentName = commentMap.get(Constants.COMMENT_USER_NAME);
                SpannableString commentTo = new SpannableString(commentName);
               /*  TextViewSpan clickableSpan = new TextViewSpan(commentName, mActivity, -1, 0);
                clickableSpan.setInfo(commentMap);
                 commentTo.setSpan(clickableSpan, 0, commentName.length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);*/
                ForegroundColorSpan buleSpan = new ForegroundColorSpan(getResources().getColor(R.color.weekly_comment_name));
                commentTo.setSpan(buleSpan, 0, commentName.length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                comment.append(commentTo);
                comment.append(":");
                SpannableStringBuilder ssb = handler(comment,
                        commentMap.get(Constants.COMMENT_CONTENT));
                comment.append(ssb);
                comment.setBackgroundResource(R.color.talk_item_comment_bg);
              /*  comment.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                    }
                });
                comment.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View view) {
                        return true;
                    }
                });*/
                mLayoutCommentList.addView(comment);
            }
        } else {
            mLayoutCommentList.setVisibility(View.GONE);

        }


    }

    @Override
    public void onClick(View v) {
        if (Constants.isFastClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.title_ll_back:
                finish();
                break;
            case R.id.tv_weekly_detail_list_item_comment:
                showBottomLayout();
                break;
            case R.id.iv_weekly_detail_list_emotion:
                boolean visible = mEmotionLayout.getVisibility() == View.VISIBLE;
                if (visible) {
                    mIvEmotiom.setImageDrawable(getResources().getDrawable(R.drawable.selector_emotion_icon));
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

                } else {
                    mIvEmotiom.setImageDrawable(getResources().getDrawable(R.drawable.selector_keyboard_btn));
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(mActivity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
                mEmotionLayout.setVisibility(visible ? View.GONE : View.VISIBLE);
                break;

            case R.id.et_weekly_detail_list_input:
                visible = (mEmotionLayout.getVisibility() == View.VISIBLE);
                mIvEmotiom.setImageDrawable(getResources().getDrawable(R.drawable.selector_emotion_icon));
                if (visible) {
                    mEmotionLayout.setVisibility(View.GONE);
                }
                break;

            case R.id.tv_weekly_detail_list_send:
                addCommentMsg(mSendMessage, mWeeklyId);

                break;

        }

    }

    /**
     * 显示等待的dialog
     */
    private void httpReqDlgShow() {
        if (mWaitDialog == null) {
            mWaitDialog = AllDialogUtil.getInstance(mActivity).waitDialog();
            mWaitDialog.show();
        }

    }

    /**
     * 取消等待的dialog
     */
    private void httpReqDlgDismiss() {
        if (mWaitDialog != null && mWaitDialog.isShowing()) {
            mWaitDialog.dismiss();
            mWaitDialog = null;
        }
    }

    private SpannableStringBuilder handler(final TextView gifTextView, String content) {
        SpannableStringBuilder sb = new SpannableStringBuilder(content);
        String regex = "(\\#\\[face/png/f_static_)\\d{3}(.png\\]\\#)";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(content);
        while (m.find()) {
            String tempText = m.group();
            try {
                String num = tempText.substring("#[face/png/f_static_".length(), tempText.length() - ".png]#".length());
                String gif = "face/gif/f" + num + ".gif";
                /**
                 * 如果open这里不抛异常说明存在gif，则显示对应的gif
                 * 否则说明gif找不到，则显示png
                 * */
                InputStream is = getAssets().open(gif);
                sb.setSpan(new AnimatedImageSpan(new AnimatedGifDrawable(is, new AnimatedGifDrawable.UpdateListener() {
                            @Override
                            public void update() {
                                gifTextView.postInvalidate();
                            }
                        })), m.start(), m.end(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                is.close();
            } catch (Exception e) {
                String png = tempText.substring("#[".length(), tempText.length() - "]#".length());
                try {
                    int resID = getResources().getIdentifier(png.split("/")[2].substring(0, png.split("/")[2].indexOf(".")), "drawable", getApplicationInfo().packageName);
                    sb.setSpan(new ImageSpan(mActivity, BitmapFactory.decodeResource(getResources(), resID)), m.start(), m.end(),
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//                    sb.setSpan(new ImageSpan(mContext, BitmapFactory.decodeStream(mContext.getAssets().open(png))), m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
//                e.printStackTrace();
            }
        }
        return sb;
    }

    /**
     * 获取详情
     */
    private void getWeeklyDetail() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_WEEKLY_ID, mWeeklyId));
        WeeklyDetailMsg message = new WeeklyDetailMsg(mHandler.obtainMessage(WEEKLY_DETAIL));
        message.mApi = AsynHttpClient.API_EVENT_WEEKLY_DETAIL;
        message.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(message);
    }


    TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            mSendMessage = mEtCommentEdit.getText().toString().trim();
            if (!StringUtil.isEmpty(mSendMessage)) {
                mTvSend.setVisibility(View.VISIBLE);
            } else {
                mTvSend.setVisibility(View.GONE);
            }

        }
    };

    /**
     * 发表评论
     */
    private void addCommentMsg(String comment, String weeklyId) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_WEEKLY_ID, weeklyId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_CONTENT, comment));
        GetMsgHttpReceiver getMsgHttpReceiver = new GetMsgHttpReceiver(mHandler.obtainMessage(ADD_COMMENT_MSG));
        getMsgHttpReceiver.mApi = AsynHttpClient.API_EVENT_WEEKLY_COMMENT;
        getMsgHttpReceiver.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(getMsgHttpReceiver);
    }

    /**
     * 弹出回复框
     */
    public void showBottomLayout() {
        mLlBottomLayout.setVisibility(View.VISIBLE);
        boolean visible = (mEmotionLayout.getVisibility() == View.VISIBLE);
        if (visible) {
            mIvEmotiom.setImageDrawable(getResources().getDrawable(R.drawable.selector_emotion_icon));
            mEmotionLayout.setVisibility(View.GONE);
        }
        ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

        mEtCommentEdit.setText("");
        mEtCommentEdit.requestFocus();
        mEtCommentEdit.setHint("发表评论");
    }
}
